//
//  AlbumsViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/6.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD
import SwiftyStoreKit

private let reuseIdentifier = "AlbumCell"
private let headerIdentifier = "GoupPurchaseView"

private struct GroupPurchaseInfo {
  var groupID: Int
  var groupName: String
  var isFree: Bool
  var iapIdentifier: String?
  var iapPrice: Int
  var isFinished: Bool
}

class AlbumsViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var collectionView: UICollectionView!
  
  // MARK: - Private vars
  
  private var isFirstLoaded = true
  private var albumsArray: [Album]?
  private var groupPurchaseInfo: GroupPurchaseInfo?
  private var isGroupPurchased = false
  private var isAllAlbumsInGroupPurchased = false
  private var groupPurchasedNote: String?
  
  private var header: GroupPurcaseView?
  
  // MARK: - Private methods
  
  @objc private func loadData() {
    if let groupIdentifier = simpleGroup?.identifier {
      var urlString = ""
      if let currentUser = UserManager.shared.currentUser {
        urlString = APIURLStrings.albumsOfGroupWithPurchaseInfo(identifier: groupIdentifier, listenerIdentifier: currentUser.identifier)
      } else {
        urlString = APIURLStrings.albumsOfGroup(identifier: groupIdentifier)
      }
      API.shared.requestAPI(urlString, method: .get, successCallback: { json in
        
        if json["group"].exists() {
          let groupJSON = json["group"]
          self.groupPurchaseInfo = GroupPurchaseInfo (
            groupID: groupJSON["id"].intValue,
            groupName: groupJSON["name"].stringValue,
            isFree: groupJSON["is_free"].boolValue,
            iapIdentifier: groupJSON["iap_identifier"].string,
            iapPrice: groupJSON["iap_price"].intValue,
            isFinished: groupJSON["is_finished"].boolValue
          )
          loggingPrint("Group finished: \(groupJSON["is_finished"].boolValue)")
        } else {
          self.groupPurchaseInfo = nil
        }
        
        // check exchange state
        if json["purchase_status"].exists() {
          self.isGroupPurchased = json["purchase_status"]["purchased"].boolValue
          self.isAllAlbumsInGroupPurchased = json["purchase_status"]["is_all_albums_purchased"].boolValue
          self.groupPurchasedNote = json["purchase_status"]["note"].string
        }
        
        // check iap state
        if self.isGroupPurchased == false && self.isAllAlbumsInGroupPurchased == false {
          do {
            if let iapPurchasedItem = try IAPPurchasedItem.get(contentType: "group", id: groupIdentifier){
              self.isGroupPurchased = true
              self.groupPurchasedNote = "已于\(iapPurchasedItem.date!.toString(format: .fullDateWithChinese))购买"
            }
          } catch { }
        }
        
        if let albumsJSON = json["albums"].arrayObject as? [[String: Any]] {
          EntityManager.sync (
            type: Album.self,
            rawObject: albumsJSON,
            operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
            completion: { error, albums in
              if error == nil {
                self.albumsArray = albums!
              } else {
                self.albumsArray = nil
              }
              self.collectionView.reloadData()
          })
        } else {
          self.albumsArray = nil
          self.collectionView.reloadData()
        }
        
        UIView.animate(withDuration: 0.3) {
          self.collectionView.alpha = 1
        }
        
      }) { (message, code) in
        loggingPrint("[\(code)]: \(message)")
      }
    }
  }
  
  private func addNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: .tokenExchangeSuccess, object: nil)
  }
  
  // MARK: - Public vars
  
  var simpleGroup: SimpleGroup? {
    didSet {
      if simpleGroup != nil {
        title = simpleGroup!.name
      }
    }
  }
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    addNotifications()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    if isFirstLoaded {
      collectionView!.alpha = 0
    }
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    if isFirstLoaded {
      loadData()
      isFirstLoaded = false
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  deinit {
    NotificationCenter.default.removeObserver(self)
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

// MARK: - UICollectionViewDataSource

extension AlbumsViewController: UICollectionViewDataSource {
  
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
  }
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return albumsArray?.count ?? 0
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! AlbumCell
    
    if let album = albumsArray?[indexPath.row] {
      cell.prepare(album: album)
    }
    return cell
  }
  
  func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if kind == UICollectionView.elementKindSectionHeader {
      let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier, for: indexPath) as! GroupPurcaseView
      if let info = groupPurchaseInfo {
        header.prepare (
          price: info.iapPrice,
          purchased: isGroupPurchased,
          allAlbumInGroupPurchased: isAllAlbumsInGroupPurchased,
          purchasedNote: groupPurchasedNote,
          isFinished: info.isFinished
        )
      }
      self.header = header
      header.delegate = self
      return header
    } else {
      return UICollectionReusableView()
    }
  }
}

// MARK: - UICollectionViewDelegate

extension AlbumsViewController: UICollectionViewDelegate {
  
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let album = albumsArray?[indexPath.row] {
      let storyboard = UIStoryboard(name: "ContentBrowsing", bundle: nil)
      let albumDetailViewController = storyboard.instantiateViewController(withIdentifier: "AlbumDetailViewController") as! AlbumDetailViewController
      albumDetailViewController.albumIdentifier = Int(album.id)
      navigationController?.pushViewController(albumDetailViewController, animated: true)
    }
  }
}

extension AlbumsViewController: UICollectionViewDelegateFlowLayout {
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (collectionView.width - 32) / 2 - 8
    let height = width * 185 / 143 - 30
    return CGSize(width: width, height: height)
  }
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    if let info = groupPurchaseInfo, info.isFree == true {
      return CGSize.zero
    } else {
      return CGSize (
        width: collectionView.width,
        height: GroupPurcaseView.defaultHeight
      )
    }
  }
}

extension AlbumsViewController: GroupPurchaseViewDelegate {
  
  private func displayLoginView() {
    let alert = UIAlertController (
      title: "尚未登录",
      message: "请登录后购买",
      cancelTitle: "取消",
      cancelHandler: nil,
      confirmTitle: "登录") { _ in
        let loginViewController = UIStoryboard(name: "Account", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        loginViewController.addCloseButton()
        let nav = BaseNavigationController(rootViewController: loginViewController, dismissDelegate: self)
        nav.isPresentedModally = true
        self.present(nav, animated: true)
    }
    present(alert, animated: true)
  }
  
  func buySession() {
    if UserManager.shared.currentUser != nil {
      if let purchaseInfo = groupPurchaseInfo {
        let body: [String: Any] = [
          "type": 0,
          "ref_id": purchaseInfo.groupID
        ]
        HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
        API.shared.requestAPI (
          APIURLStrings.exchangeContent,
          method: .post,
          body: body,
          header: API.shared.memeberHeader,
          successCallback: { json in
            
            HUD.flash(.labeledSuccess(title: "兑换成功", subtitle: nil), delay: 1.5)
            NotificationCenter.default.post(name: .reloadPurchasedHistory, object: nil)
            
            // update purchase status
            self.isGroupPurchased = true
            if let info = self.groupPurchaseInfo,
              let header = self.header {
              header.prepare (
                price: info.iapPrice,
                purchased: self.isGroupPurchased,
                allAlbumInGroupPurchased: self.isAllAlbumsInGroupPurchased,
                purchasedNote: "已于\(Date().toString(format: .fullDateWithChinese))兑换",
                isFinished: info.isFinished
              )
            }
            NotificationCenter.default.post(name: .tokenExchangeSuccess, object: nil)
            
        }, errorCallback: { (message, code) in
          // MARK: - [WARNING]: Using static string for checking state
          if message == "狮羊曼尼不足，请先充值" {
            HUD.hide()
            let alert = UIAlertController (
              title: "兑换失败",
              message: message,
              cancelTitle: "取消",
              cancelHandler: nil,
              confirmTitle: "去充值",
              confirmHandler: { _ in
                self.performSegue(withIdentifier: "ShowTokenViewControllerFromAlbums", sender: nil)
            })
            self.present(alert, animated: true)
          } else {
            HUD.flash(.labeledError(title: "兑换失败", subtitle: message), delay: 1.5)
          }
        })
      }
    } else {
      displayLoginView()
    }
  }
  
  func displayPurchaseInfo() {
    let alert = UIAlertController (
      title: "全季售价",
      message: "该售价为整季所有节目售价，购买全季后您将获得该季已经发布和之后更新的所有节目。",
      cancelTitle: "知道了",
      cancelHandler: nil)
    present(alert, animated: true)
  }
}

// MARK: - BaseNavigationControllerDismissDelegate

extension AlbumsViewController: BaseNavigationControllerDismissDelegate {
  func dismiss(navigationController: BaseNavigationController, completion: (() -> Void)?) {
    loadData()
    dismiss(animated: true, completion: completion)
  }
}
